package com.chenxin.common.core.redis;

import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
@SuppressWarnings("unchecked")
@Component
public class MyCache implements Cache{
    private Map<String, Object> storage = new ConcurrentHashMap<>();

    @Override
    public String getName() {
        return "myCache";
    }

    @Override
    public Object getNativeCache() {
        return storage;
    }

    public boolean hasKey(String key) {
        return storage.containsKey(key);
    }

    @Override
    public ValueWrapper get(Object key) {
        String k = key.toString();
        Object value = storage.get(k);

        return Objects.isNull(value) ? null : new SimpleValueWrapper(value);
    }

    @Override
    public <T> T get(Object key, Class<T> type) {
        Object value = storage.get(key.toString());
        return value != null ? type.cast(value) : null; // 安全类型转换
    }

    @Override
    public <T> T get(Object key, Callable<T> valueLoader) {
        T value = (T) storage.get(key.toString()); // 需要@SuppressWarnings
        if (value == null) {
            try {
                value = valueLoader.call();
                put(key, value);
            } catch (Exception e) {
                throw new ValueRetrievalException(key, valueLoader, e);
            }
        }
        return value;
    }

    @Override
    public void put(Object key, Object value) {
        if (Objects.isNull(value)) {
            return;
        }
        //存值
        storage.put(key.toString(), value);
    }

    @Override
    public void evict(Object key) {
        storage.remove(key.toString());
    }

    public boolean deleteObject(final Collection collection) {
        collection.forEach(o -> {
            storage.remove(o.toString());
        });
        return true;
    }

    public Collection<String> keys(final String pattern) {
        return storage.keySet();
    }

    @Override
    public void clear() {

    }
}
